package com.itheima.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.LogRecord;
@WebFilter("/*")
public class loginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        //判断访问资源路径是否和登录注册相关
        String[] urls={"/login.jsp","/imgs/","/css/","/loginServlet","/registerServlet","/register.jsp","/checkCodeServlet"};
        //获取当前访问的资源路径
        String url = req.getRequestURL().toString();
        //循环判断
        for (String u:urls) {
            if(url.contains(u)){
                chain.doFilter(request,response);
                return;
            }
        }
        HttpSession session = req.getSession();
        Object user=session.getAttribute("user");
        //2.判断user是否为none
        if (user!=null){
            chain.doFilter(request,response);
        }
        else {
            //没有登录,跳转到登录页面
            req.setAttribute("login_msg","你尚未登录");
            req.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }
    public  void  init(FilterConfig config)throws ServletException {
    }
    public void destroy(){
    }

}
